/**
 * Copyright (c) 2025 Bytedance Ltd. and/or its affiliates
 * SPDX-License-Identifier: MIT
 */

import { useEffect, useState } from 'react';
import { Modal, Button } from 'antd';

import { usePlaygroundTools, useClientContext } from '@flowgram.ai/free-layout-editor';

import { runWorkflow } from '../utils/workflow-runner';

export function Tools() {
  const { history, document } = useClientContext();
  const tools = usePlaygroundTools();
  const [canUndo, setCanUndo] = useState(false);
  const [canRedo, setCanRedo] = useState(false);
  const [isModalOpen, setIsModalOpen] = useState(false); // 新增状态控制弹窗

  const handleRun = () => {
    console.log('Running workflow...');
    runWorkflow(document);
  };
  //下载流程模型文件
  const handleDownLoad = () => {
    console.log('Downloading workflow...');
    // 可选：下载为 JSON 文件
    console.log(document.toJSON());
    // 显示弹窗
    setIsModalOpen(true);
  };

  // 关闭弹窗
  const handleCloseModal = () => {
    setIsModalOpen(false);
  };

  useEffect(() => {
    const disposable = history.undoRedoService.onChange(() => {
      setCanUndo(history.canUndo());
      setCanRedo(history.canRedo());
    });
    return () => disposable.dispose();
  }, [history]);

  return (
    <div
      style={{ position: 'absolute', zIndex: 10, bottom: 16, left: 226, display: 'flex', gap: 8 }}
    >
      <button onClick={() => tools.zoomin()}>ZoomIn</button>
      <button onClick={() => tools.zoomout()}>ZoomOut</button>
      <button onClick={() => tools.fitView()}>Fitview</button>
      <button onClick={() => tools.autoLayout()}>AutoLayout</button>
      <button onClick={() => history.undo()} disabled={!canUndo}>
        Undo
      </button>
      <button onClick={() => history.redo()} disabled={!canRedo}>
        Redo
      </button>
      <span>{Math.floor(tools.zoom * 100)}%</span>
      <button onClick={handleRun}>自动校验</button>
      <button onClick={handleDownLoad}>Download</button>
      {/* 模型json预览弹窗 */}
      <Modal
        title="Workflow JSON"
        open={isModalOpen}
        onCancel={handleCloseModal}
        footer={[
          <Button key="close" onClick={handleCloseModal}>
            关闭
          </Button>,
        ]}
        width={800}
      >
        <pre
          style={{
            maxHeight: '60vh', // 限制最大高度为视窗高度的60%
            overflow: 'auto', // 超出时显示滚动条
            whiteSpace: 'pre-wrap',
            wordWrap: 'break-word',
          }}
        >
          {JSON.stringify(document.toJSON(), null, 2)}
        </pre>
      </Modal>
    </div>
  );
}
